import { createRouter, createWebHistory } from 'vue-router'
import useUser from "@/hooks/user"
import { authUrlList } from '@/config/settings'
import BaseLayout from "@/layout/base-layout.vue";

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "home" */ '../views/Login.vue')
  },
  {
    path: '/',
    name: 'BaseLayout',
    component: BaseLayout,
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
      },
      {
        path: '/article',
        name: 'Article',
        component: () => import(/* webpackChunkName: "article" */ '../views/Article.vue')
      },
      {
        path: '/tag',
        name: 'Tag',
        component: () => import(/* webpackChunkName: "tag" */ '../views/Tag.vue')
      },
      {
        path: '/about',
        name: 'About',
        component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
      },
      {
        path: '/post',
        name: 'Post',
        component: () => import(/* webpackChunkName: "post" */ '../views/Post.vue')
      }
    ]
  },
  {
    path: '/poster',
    name: 'Poster',
    component: () => import(/* webpackChunkName: "poster" */ '../views/Poster.vue')
  },
]

const { getToken } = useUser()
const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL),
  history: createWebHistory(process.env.NODE_ENV === 'production' ? '/blog/' : ''),
  routes
})

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 不在白名单并且没有token
  if (authUrlList.includes(to.path) && !token) return next('/login')
  // ...
  // 返回 false 以取消导航
  return next()
})

export default router
